import { defineStore } from "pinia";
import { reactive } from "vue";
import { getToken, removeToken, setToken } from "../utils/auth";
import { getUserInfo, login as loginApi, logout as logoutApi } from "../api/login";
import { SCMessage } from "@sribd/sc-ui";

interface User {
    id: number | undefined;
    token: string | undefined;
    username: string;
    menus: number[];
    requestMenuNum: number;
}

export const useUserStore = defineStore("user", () => {
    const user = reactive<User>({
        id: undefined,
        token: getToken(),
        username: "",
        menus: [], // 有权限的菜单
        requestMenuNum: 0,
    });

    async function login(name: string, password: string) {
        try {
            const token = await loginApi(name, password);
            token && setToken(token);
        } catch (error) {
            SCMessage({
                message: error?.msg || "登录失败",
                type: "error",
            });
        }
    }

    async function getInfo() {
        try {
            const res: any = await getUserInfo();
            user.id = res.id;
            user.token = getToken();
            user.username = res.username;
            user.menus = res.permissionList;
            return res;
        } catch (error) {
            console.log(error);
            return {};
        }
    }

    async function logout() {
        try {
            await logoutApi();
            resetToken();
            // setSession("");
        } catch (error) {}
    }

    function resetToken() {
        removeToken();
        user.token = "";
        user.id = undefined;
        user.username = "";
    }
    function setMenus(menus: number[] = []) {
        user.menus = menus;
    }
    function getRequestMenuNum() {
        return user.requestMenuNum;
    }
    function setRequestMenuNum() {
        user.requestMenuNum++;
    }

    return {
        user,
        login,
        logout,
        getInfo,
        resetToken,
        setMenus,
        getRequestMenuNum,
        setRequestMenuNum,
    };
});
